<?php
namespace User\Controller;

use Common\Controller\AdminbaseController;

class RealuserController extends AdminbaseController
{
    function _initialize()
    {
        parent::_initialize();
        $this->users_model = M("RealUsers");
        $this->prizesorder_model = M("PrizesOrder");
        $this->wxpayorder_model = M("WxPayOrder");
        $this->events_model = M("Events");
        $this->card_model = M("Card");
        $this->userwallet_model = M("UserWallet");
        $this->backup_path = '/data/';

        $this->status = array(
            array(id => 1, name => '正常'),
            array(id => 2, name => '锁定'),
            array(id => 3, name => '停用'),
        );
        $this->register_from = array(
            array(id => 1, name => '微信'),
            array(id => 2, name => '微博'),
            array(id => 3, name => 'APP'),
        );
        $this->gender = array(
            array(id => 0, name => '保密'),
            array(id => 1, name => '男'),
            array(id => 2, name => '女'),
        );
        $this->wxpay_status = array(
            array(id => 1, name => '成功'),
            array(id => 2, name => '失败'),
        );
        $this->wxpay_paytype = array(
            array(id => 1, name => '普通红包'),
            array(id => 2, name => '提现红包'),
        );
        $this->order_status = array(
            array(id => 1, name => '用户中奖'),
            array(id => 2, name => '用户领取'),
            array(id => 3, name => '用户使用'),
            array(id => 4, name => '未领过期'),
        );
    }

    function index()
    {
        if (I('param.')) {
            if (I('param.user_status')) {
                $search[] = array('status' => I('param.user_status'));
                $_GET['user_status'] = I('param.user_status');
            }
            if (I('param.start_time')) {
                $search[] = array('date(last_login)' => array('egt', I('param.start_time')));
                $_GET['start_time'] = I('param.start_time');
            }
            if (I('param.end_time')) {
                $search[] = array('date(last_login)' => array('elt', I('param.end_time')));
                $_GET['end_time'] = I('param.end_time');
            }
            if (I('param.keyword')) {
                $search[] = array('nickname' => array("like", "%" . I('param.keyword') . "%"));
                $_GET['keyword'] = I('param.keyword');
            }
        }
        $count = $this->users_model->where($search)->count();
        $page = $this->page($count, 50);
        $lists = $this->users_model
            ->where($search)
            ->limit($page->firstRow . ',' . $page->listRows)
            ->order("created_at DESC")
            ->select();
        $roleid =  get_current_adminrole_id();

        $this->assign('lists', $lists);
        $this->assign('status', $this->status);
        $this->assign('register_from', $this->register_from);
        $this->assign('page', $page->show('Admin'));
        $this->assign('count', $count);
        $this->assign('roleid', $roleid);
        $this->display();
    }

    function htRecharge()
    {
        if (!get_current_admin_id()) {
            /* 这里面添加权限判断
             */
            $this->error(sp_get_current_user() . "您没有权限");
        }
        $roleid =  get_current_adminrole_id();
        if ($roleid != 1 && $roleid != 3 && $roleid != '') {
            $this->error(sp_get_current_user() . "您没有权限");
        }

        $password = I('post.password');
        $amount = I('post.amount');
        $userid = I('post.userid');
        $remarks = I('post.remarks');
        $amount = $amount*100;
        if ($amount && $userid) {
            /*$tx_pass = D('users')->where('id='.get_current_admin_id())->getField('tx_pass');
            if (!password_verify($password ,$tx_pass)) {
                $this->error('密码错误');
            }*/

            $wallet_model = D('user_wallet');

            $wallet_model->startTrans();
            try {
                $data['userid'] = $userid;
                $data['admin_id'] = get_current_admin_id();
                $data['amount'] = $amount;
                $data['remarks'] = '后台添加:' . $remarks;
                D('recharge_order')->add($data);

                $where[real_user_id] = $userid;
                $wallet_model->where($where)->setInc('money', $amount);
                $result = true;
            } catch (\Exception $exc) {
                $result = FALSE;
                \Think\Log::record('htRecharge catch Exception' . $wallet_model->getDbError());
                \Think\Log::record('htRecharge catch Exception' . $exc->getMessage());
            }

            if ($result) {
                //提交事务
                $this->card_model->commit();
            } else {
                // 事务回滚
                $this->card_model->rollback();
                \Think\Log::record('htRecharge  fail rollback');
                $this->error('操作失败');
            }
        }
        $user = $this->users_model->where(array("id" => I("get.id")))->find();
        $userwallet = $this->userwallet_model->where(array("real_user_id" => I("get.id")))->find();
        $this->assign('user', $user);
        $this->assign('userwallet', $userwallet);

        $this->display('recharge');
    }

    function userinfo()
    {
        $user = $this->users_model->where(array("id" => I("get.id")))->find();
        $prizesorder = $this->prizesorder_model->where(array("openid" => $user['weixin_id']))->count();
        $wxpayorder = $this->wxpayorder_model->where(array("openid" => $user['weixin_id']))->count();
        $userwallet = $this->userwallet_model->where(array("real_user_id" => I("get.id")))->find();
        $this->assign('prizesorder', $prizesorder);
        $this->assign('wxpayorder', $wxpayorder);
        $this->assign('userwallet', $userwallet);
        $this->assign('user', $user);
        $this->assign('status', $this->status);
        $this->assign('register_from', $this->register_from);
        $this->assign('gender', $this->gender);
        $this->display();
    }

    function prizes()
    {
        $id = intval(I("get.id"));
        $user = $this->users_model->where(array("id" => $id))->find();
        $count = $this->prizesorder_model->where(array("openid" => $user['weixin_id']))->count();
        $page = $this->page($count, 50);
        $prizesorder = $this->prizesorder_model
            ->where(array("openid" => $user['weixin_id']))
            ->limit($page->firstRow . ',' . $page->listRows)
            ->order("id DESC")
            ->select();
        $this->assign('prizesorder', $prizesorder);
        $this->assign('page', $page->show('Admin'));
        $this->display();
    }

    function wxpay()
    {
        $id = intval(I("get.id"));
        $user = $this->users_model->where(array("id" => $id))->find();
        $count = $this->wxpayorder_model->where(array("openid" => $user['weixin_id']))->count();
        $page = $this->page($count, 50);
        $wxpayorder = $this->wxpayorder_model
            ->where(array("openid" => $user['weixin_id']))
            ->limit($page->firstRow . ',' . $page->listRows)
            ->order("id DESC")
            ->select();
        $this->assign('wxpayorder', $wxpayorder);
        $this->assign('wxpay_status', $this->wxpay_status);
        $this->assign('wxpay_paytype', $this->wxpay_paytype);
        $this->assign('page', $page->show('Admin'));
        $this->display();
    }

    public function prizelist()
    {
        if (I('param.card_type')) {
            $search[] = array('card_type' => I('param.card_type'));
            $_GET['card_type'] = I('param.card_type');
        }
        if (I('param.order_status')) {
            $search[] = array('order_status' => I('param.order_status') - 1);
            $_GET['order_status'] = I('param.order_status');
        }
        if (I('param.event_id')) {
            $search[] = array('event_id' => I('param.event_id'));
            $_GET['event_id'] = I('param.event_id');
        }
        if (I('param.start_time')) {
            $search[] = array('date(winning_time)' => array('egt', I('param.start_time')));
            $_GET['start_time'] = I('param.start_time');
        }
        if (I('param.end_time')) {
            $search[] = array('date(winning_time)' => array('elt', I('param.end_time')));
            $_GET['end_time'] = I('param.end_time');
        }
        $count = $this->prizesorder_model
            ->where($search)
            ->count();
        $page = $this->page($count, 50);
        $lists = $this->prizesorder_model
            ->where($search)
            ->limit($page->firstRow . ',' . $page->listRows)
            ->order("winning_time DESC")
            ->select();
        if ($lists) {
            foreach ($lists as $list) {
                $openid[] = $list['openid'];
                $eventid[] = $list['event_id'];
                $cardid[] = $list['card_id'];
            }
            $users = $this->users_model
                ->where(array('weixin_id' => array('in', $openid)))
                ->select();
            $events = $this->events_model
                ->where(array('id' => array('in', $eventid)))
                ->select();
            $cards = $this->card_model
                ->where(array('id' => array('in', $cardid)))
                ->select();
            $this->assign('users', $users);
            $this->assign('events', $events);
            $this->assign('cards', $cards);
        }
        $this->assign('count', $count);
        $this->assign('lists', $lists);
        $this->assign('ostatus', $this->order_status);
        $this->assign('prize_type', C('CARD_TYPE'));
        $this->assign('page', $page->show('Admin'));
        $this->display();
    }

    public function download()
    {
        $backup_name = isset($_GET['backup']) && trim($_GET['backup']) ? trim($_GET['backup']) :
            $this->error('请选择文件名称！');
        $file = isset($_GET['file']) && trim($_GET['file']) ? trim($_GET['file']) : $this->
        error('请选择文件文件！');
        $sql_file = SITE_PATH . $this->backup_path . $backup_name . '/' . $file;
        if (file_exists($sql_file)) {
            header('Content-type: application/unknown');
            header('Content-Disposition: attachment; filename="' . $file . '"');
            header("Content-Length: " . filesize($sql_file) . "; ");
            readfile($sql_file);
        } else {
            $this->error('文件不存在！');
        }
    }

    public function export_csv($filename, $data)
    {
        $file_hwnd = fopen('data/runtime/' . $filename, "w");
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=" . $filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        fwrite($file_hwnd, $data);
        fclose($file_hwnd);
    }

    public function indexoutcsv()
    {
        if (I('param.')) {
            if (I('param.user_status')) {
                $search[] = array('status' => I('param.user_status'));
            }
            if (I('param.start_time')) {
                $search[] = array('date(last_login)' => array('egt', I('param.start_time')));
            }
            if (I('param.end_time')) {
                $search[] = array('date(last_login)' => array('elt', I('param.end_time')));
            }
            if (I('param.keyword')) {
                $search[] = array('nickname' => array("like", "%" . I('param.keyword') . "%"));
            }
            $_GET['user_status'] = I('param.user_status');
            $_GET['start_time'] = I('param.start_time');
            $_GET['end_time'] = I('param.end_time');
            $_GET['keyword'] = I('param.keyword');
        }
        if (!I('param.user_status') && !I('param.start_time') && !I('param.end_time') && !I('param.keyword')) {
            $this->error('请选择查询条件！');
        }
        $users = $this->users_model->where($search)->select();
        if (count($users) > 20000) {
            $this->error('导出数据过多会导致内存溢出！请分别查询导出！');
        }
        $head[] = iconv('utf-8', 'GBK', ",用户名,昵称,电话,地址,注册来源,注册日期,登录时间,登录IP\r\n");
        $register = $this->register_from;
        if ($users) {
            set_time_limit(0);
            foreach ($users as $user) {
                $content[] = iconv('utf-8', 'GBK', $user['username']) . "," .
                    iconv('utf-8', 'GBK', $user['nickname']) . "," .
                    iconv('utf-8', 'GBK', $user['phone']) . "," .
                    iconv('utf-8', 'GBK', $user['address']) . "," .
                    iconv('utf-8', 'GBK', $register[$user['register_from'] - 1]['name']) . "," .
                    iconv('utf-8', 'GBK', $user['created_at']) . "," .
                    iconv('utf-8', 'GBK', $user['last_login']) . "," .
                    iconv('utf-8', 'GBK', $user['last_login_ip']) . "\r\n";
            }
//		$this->error(json_encode($prizesorder));
        }
        $csvname = time() . '.csv';
        $str = implode(',', array_merge($head, $content));
        $this->export_csv($csvname, $str);
        $this->success('导出完成', U('Realuser/download', array('backup' => 'runtime', 'file' => "$csvname")));
    }

    public function prizeoutcsv()
    {
        if (I('param.')) {
            if (I('param.card_type')) {
                $search[] = array('card_type' => I('param.card_type'));
            }
            if (I('param.order_status')) {
                $search[] = array('order_status' => I('param.order_status') - 1);
            }
            if (I('param.event_id')) {
                $search[] = array('event_id' => I('param.event_id'));
            }
            if (I('param.start_time')) {
                $search[] = array('date(winning_time)' => array('egt', I('param.start_time')));
            }
            if (I('param.end_time')) {
                $search[] = array('date(winning_time)' => array('elt', I('param.end_time')));
            }
            $_GET['card_type'] = I('param.card_type');
            $_GET['order_status'] = I('param.order_status');
            $_GET['event_id'] = I('param.event_id');
            $_GET['start_time'] = I('param.start_time');
            $_GET['end_time'] = I('param.end_time');
        }
        if (!I('param.card_type') && !I('param.order_status') && !I('param.event_id') && !I('param.start_time') && !I('param.end_time')) {
            $this->error('请选择查询条件！');
        }
        $prizesorder = $this->prizesorder_model->where($search)->select();
        if (count($users) > 20000) {
            $this->error('导出数据过多会导致内存溢出！请分别查询导出！');
        }
        $head[] = iconv('utf-8', 'GBK', ",用户名,昵称,电话,地址,中奖类型,活动名称,物料名称,物料编号,中奖时间,状态\r\n");
        $ostatus = $this->order_status;
        $prize_type = C('CARD_TYPE');
        if ($prizesorder) {
            foreach ($prizesorder as $list) {
                $openid[] = $list['openid'];
                $eventid[] = $list['event_id'];
                $cardid[] = $list['card_id'];
            }
            $users = $this->users_model
                ->where(array('weixin_id' => array('in', $openid)))
                ->select();
            $events = $this->events_model
                ->where(array('id' => array('in', $eventid)))
                ->select();
            $cards = $this->card_model
                ->where(array('id' => array('in', $cardid)))
                ->select();
            set_time_limit(0);
            foreach ($prizesorder as $order) {
                foreach ($users as $user) {
                    if ($user['weixin_id'] == $order['openid']) {
                        $card_type = $prize_type[$order['card_type'] - 1]['name'];
                        $order_status = $ostatus[$order['order_status']]['name'];
                        foreach ($events as $event) {
                            if ($event['id'] == $order['event_id']) {
                                $event_name = $event['event_name'];
                            }
                        }
                        foreach ($cards as $card) {
                            if ($card['id'] == $order['card_id']) {
                                $card_name = $card['card_name'];
                            }
                        }
                        $content[] = iconv('utf-8', 'GBK', $user['realname']) . "," .
                            iconv('utf-8', 'GBK', $user['nickname']) . "," .
                            iconv('utf-8', 'GBK', $user['phone']) . "," .
                            iconv('utf-8', 'GBK', $user['address']) . "," .
                            iconv('utf-8', 'GBK', $card_type) . "," .
                            iconv('utf-8', 'GBK', $event_name) . "," .
                            iconv('utf-8', 'GBK', $card_name) . "," .
                            iconv('utf-8', 'GBK', $order['card_num']) . "," .
                            iconv('utf-8', 'GBK', $order['winning_time']) . "," .
                            iconv('utf-8', 'GBK', $order_status) . "\r\n";
                    }
                }
            }
//		$this->error(json_encode($prizesorder));
        }
        $csvname = time() . '.csv';
        $str = implode(',', array_merge($head, $content));
        $this->export_csv($csvname, $str);
        $this->success('导出完成', U('Realuser/download', array('backup' => 'runtime', 'file' => "$csvname")));
    }
}